﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Finbook.Mvc.Infrastructure
{
    public class Pager
    {
        public int PageIndex { get; set; }
        public int PageCount { get; set; }
        public int Total { get; set; }
        public int PageSize { get; set; }
        public int MaxPagerCount { get; set; }
        public string UrlPattern { get; set; }
        public string CurrentLinkClassName { get; set; }
        private Pager()
        {
            MaxPagerCount = 5;
            CurrentLinkClassName = "shop-link";
        }
        private Pager(int total, int pageIndex = 1, int pageSize = 10)
            : this()
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            Total = total;
            PageCount = (int)Math.Ceiling(Total * 1.0f / PageSize);
            UrlPattern = $"/Home/GetPager?pageIndex={{0}}&pageSize={PageSize}";
        }
        public static string GetPager(int total, int pageIndex = 1, int pageSize = 10)
        {
            var pager = new Pager(total, pageIndex, pageSize);
            var startPageIndex = Math.Max(1, pager.PageIndex - pager.MaxPagerCount / 2);
            var endPageIndex = Math.Min(pager.PageCount, pager.PageIndex + pager.MaxPagerCount - 3);
            StringBuilder sb = new StringBuilder();
            sb.Append("<nav><ul class='pagination'>");
            if (startPageIndex >= 2)
            {
                sb.Append($"<li class='page-item'><a class='{pager.CurrentLinkClassName} page-link' href='{string.Format($"{pager.UrlPattern}", startPageIndex - 1)}'>&lt;</a></li>");
            }
            for (int i = startPageIndex; i <=endPageIndex; i++)
            {

                if (i == pager.PageIndex)
                {
                    sb.Append($"<li class='page-item'><a class='{pager.CurrentLinkClassName} page-link' href='javascript:;'>{i}</a></li>");
                }
                else
                {
                    var url = string.Format($"{pager.UrlPattern}", i);
                    sb.Append($"<li class='page-item'><a class='page-link' href='{url}'>{i}</a></li>");
                }
            }
            if (endPageIndex < pager.PageCount)
            {
                sb.Append($"<li class='page-item'><a class='{pager.CurrentLinkClassName} page-link' href='{string.Format($"{pager.UrlPattern}", endPageIndex + 1)}'>&gt;</a></li>");
            }
            sb.Append("</ul></nav>");
            return sb.ToString();
        }
    }
}
